//
//  ASTeacherCallNameConfirmViewController.m
//  AttendenceSys
//
//  Created by ld on 16/1/28.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "ASTeacherCallNameConfirmViewController.h"

@interface ASTeacherCallNameConfirmViewController ()

@end

@implementation ASTeacherCallNameConfirmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //[self setRightText:@"点名"];
    [self setRightText:@"提交"];
    //self.strNavTitle = @"点名";
    
    [self initData];
    [self initView];
    
    // Do any additional setup after loading the view.
}

-(void)rightButtonPressed:(id)sender
{
    [self save];
}

//查看课程下的学生（供点名用） http://121.42.185.124:8080/LawSchool/getStudentList.action?courseId=3&weekDay=1&courseNumer=1
-(void)getCourseStuList:(NSString*)courseId weekday:(NSString*)weekday courseNumber:(NSString*)courseNumber
{
    NSString* refer = @"getStudentList.action?";
    NSString* prefix = kASHttpUrl(refer);
    NSString* courseUrl = [NSString stringWithFormat:@"%@courseId=%@&weekDay=%@&courseNumer=%@", prefix,courseId, weekday, courseNumber];
    //NSString* courseUrl = [NSString stringWithFormat:@"%@courseId=%@&courseNumer=%@", prefix,courseId, courseNumber];
    
    [SVProgressHUD showWithStatus:@"获取课程所有学生信息" maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:courseUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        if (isSuccessRsp(jsonRsp))
        {
            NSArray* data = [jsonRsp objectForKey:kASJsonData];
            _teaCallNameInfoArr = [self parseCourseStuListInfo:data];
            if (_teaCallNameInfoArr.count * CallNameCellHeight < self.tableView.frame.size.height) {
                CGRect frame = self.tableView.frame;
                frame.size.height = _teaCallNameInfoArr.count * CallNameCellHeight;
                self.tableView.frame = frame;
            }
            
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            
            if (0 < _teaCallNameInfoArr.count) {
                [self getCallNameMsgInfo];
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

-(NSMutableArray*)parseCourseStuListInfo:(NSArray*)arr
{
   //ASLoginUserInfo
    NSMutableArray* courseArray = [[NSMutableArray alloc] init];
    for (int i=0; i<arr.count; i++) {
        ASLoginUserInfo* userInfo = [[ASLoginUserInfo alloc] init];
        NSDictionary* dic = [arr objectAtIndex:i];
        dic = [dic processDictionaryIsNSNull:dic];
        userInfo.userId = [dic objectForKey:@"pkUserId"];
        userInfo.userCode = [dic objectForKey:@"userCode"];
        userInfo.userName = [dic objectForKey:@"userName"];
        userInfo.leaveType = [dic objectForKey:@"leaveType"];
        userInfo.status = [NSString stringWithFormat:@"%d",defaultCallNameSelectTag];
        [courseArray addObject:userInfo];
    }
    return courseArray;
}

-(NSString*)getYearMonthDay:(NSDate*)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:date];
    NSString* year = [NSString stringWithFormat:@"%ld",[dateComponent year]];
    NSString* month = [NSString stringWithFormat:@"%ld",[dateComponent month]];
    NSString* day = [NSString stringWithFormat:@"%ld",[dateComponent day]];
    NSString* yearMonthDay = [NSString stringWithFormat:@"%@.%@.%@",year,month,day];
    return yearMonthDay;
}

-(void)initData
{
    
    NSString* sDate = [self getYearMonthDay:[NSDate date]];
    
    sDate = [sDate stringByReplacingOccurrencesOfString:@"." withString:@"-"];
    
    [self getCourseStuList:_subClsInfo.couseId weekday:sDate courseNumber:_subClsInfo.courseNumber];
    
    _teaCallNameInfoArr = [[NSMutableArray alloc] init];
    _callNameUserArr = [[NSMutableArray alloc] init];
    
//    ASLoginUserInfo* info = [[ASLoginUserInfo alloc] init];
//    info.userName = @"王岳伦";
//    info.leaveType = @"1";
//    info.userCode = @"12";
//    info.bSelect = NO;
//    [_teaCallNameInfoArr addObject:info];
//    
//    ASLoginUserInfo* info1 = [[ASLoginUserInfo alloc] init];
//    info1.userName = @"张小艾";
//    info1.leaveType = @"0";
//    info1.userCode = @"13";
//    info1.bSelect = NO;
//    [_teaCallNameInfoArr addObject:info1];
//    
//    ASLoginUserInfo* info2 = [[ASLoginUserInfo alloc] init];
//    info2.userName = @"李平";
//    info2.leaveType = @"2";
//    info2.userCode = @"14";
//    info2.bSelect = NO;
//    [_teaCallNameInfoArr addObject:info2];
//    
//    ASLoginUserInfo* info3 = [[ASLoginUserInfo alloc] init];
//    info3.userName = @"张明";
//    info3.leaveType = @"1";
//    info3.userCode = @"22";
//    info3.bSelect = NO;
//    [_teaCallNameInfoArr addObject:info3];
//    
//    ASLoginUserInfo* info4 = [[ASLoginUserInfo alloc] init];
//    info4.userName = @"窦B";
//    info4.leaveType = @"0";
//    info4.userCode = @"16";
//    info4.bSelect = NO;
//    [_teaCallNameInfoArr addObject:info4];
//    
//    ASLoginUserInfo* info5 = [[ASLoginUserInfo alloc] init];
//    info5.userName = @"孙亮";
//    info5.leaveType = @"1";
//    info5.userCode = @"42";
//    info5.bSelect = NO;
//    [_teaCallNameInfoArr addObject:info5];
//    
//    ASLoginUserInfo* info6 = [[ASLoginUserInfo alloc] init];
//    info6.userName = @"王峰";
//    info6.leaveType = @"2";
//    info6.userCode = @"32";
//    info6.bSelect = NO;
//    [_teaCallNameInfoArr addObject:info6];
//    
//    ASLoginUserInfo* info7 = [[ASLoginUserInfo alloc] init];
//    info7.userName = @"柳红兵";
//    info7.leaveType = @"0";
//    info7.userCode = @"82";
//    info7.bSelect = NO;
//    [_teaCallNameInfoArr addObject:info7];
}

-(void)initView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.frame = CGRectMake(0, 10, self.view.frame.size.width, (self.view.frame.size.height- 49 - 15 -10)*2/3 );
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollEnabled = YES;
    [_tableView registerClass:[TeacherCallNameConfirmCell class] forCellReuseIdentifier:NSStringFromClass([TeacherCallNameConfirmCell class])];
    [self.view addSubview:_tableView];
    
//    //存储
//    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, CallNameCellHeight*_teaCallNameInfoArr.count, CGRectGetWidth(self.view.bounds), 100)];
//    footer.backgroundColor = [UIColor clearColor];
//    
//    UIButton* saveBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    saveBtn.frame = CGRectMake(50, 50,[UIScreen mainScreen].bounds.size.width-50*2,50);
//    [saveBtn setTitle:@"开始点名" forState:UIControlStateNormal];
//    saveBtn.layer.cornerRadius = 4.5;
//    [saveBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
//    
//    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    saveBtn.backgroundColor = RGB(252, 120, 61);
//    saveBtn.enabled = YES;
//    [footer addSubview:saveBtn];
//    _tableView.tableFooterView = footer;
    
}

-(void)getCallNameMsgInfo
{
//    ASCallNameMsgView* asCallNameMsgView = [[ASCallNameMsgView alloc] initWithFrame:CGRectMake(0, _tableView.frame.size.height+_tableView.frame.origin.y+10, self.view.frame.size.width, (self.view.frame.size.height- 49 - 15 -10)/3)];
    ASCallNameMsgView* asCallNameMsgView = [[ASCallNameMsgView alloc] initWithFrame:CGRectMake(0, _tableView.frame.size.height+_tableView.frame.origin.y+10, self.view.frame.size.width, (self.view.frame.size.height - (self.tableView.frame.size.height + self.tableView.frame.origin.y))-10)];
    asCallNameMsgView.userCode = _userTeaCode;
    [asCallNameMsgView fetchTeacherNewMsg];
    [self.view addSubview:asCallNameMsgView];
}
//点名
-(void)save
{
   //点名接口 http://121.42.185.124:8080/LawSchool/appointStudent.action?courseId=3&weekDay=1&courseNumer=1&userCode=xiaohu&type=1 1表示请假 2迟到 3旷课 4迟到
    [self appointStudent:_callNameUserArr];
}

-(void)appointStudent:(NSMutableArray*)stuArr
{
    if (0 == stuArr.count) {
        [SVProgressHUD showErrorWithStatus:@"请选择点名的人"];
        return;
    }
    NSString* refer = @"appointStudent.action?";
    NSString* prefix = kASHttpUrl(refer);
    NSString* sDate = [self getYearMonthDay:[NSDate date]];
     //http://121.42.185.124:8080/LawSchool/appointStudent.action?reqStr = "{\"courseId\":\"4\",\"weekDay\":\"2016-05-05\",\"courseNumer\":\"1\",\"students\":[{\"userCode\":\"xiaohu\", \"type\":\"1\"},{\"userCode\":\"sjt\", \"type\":\"3\"}]}";
    NSString* student = @"[";
    for (int i=0; i<stuArr.count; i++) {
        ASLoginUserInfo* userInfo = [stuArr objectAtIndex:i];
        
        if (i == (stuArr.count-1)) {
            student = [student stringByAppendingString:[NSString stringWithFormat:@"{\"userCode\":\"%@\",",userInfo.userCode]];
            student = [student stringByAppendingString:[NSString stringWithFormat:@"\"type\":\"%@\"}",userInfo.status]];
            
        }
        else
        {
            student = [student stringByAppendingString:[NSString stringWithFormat:@"{\"userCode\":\"%@\",",userInfo.userCode]];
            student = [student stringByAppendingString:[NSString stringWithFormat:@"\"type\":\"%@\"},",userInfo.status]];
        }
    }
    student = [student stringByAppendingString:@"]"];
    
    sDate = [sDate stringByReplacingOccurrencesOfString:@"." withString:@"-"];
    
    NSString* courseUrl = [NSString stringWithFormat:@"%@reqStr={\"courseId\":\"%@\",\"weekDay\":\"%@\",\"courseNumer\":\"%@\",\"students\":%@}", prefix ,_subClsInfo.couseId ,sDate ,_subClsInfo.courseNumber,student];
    
    [SVProgressHUD showWithStatus:@"点名" maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:courseUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        jsonRsp = [jsonRsp processDictionaryIsNSNull:jsonRsp];
        if (isSuccessRsp(jsonRsp))
        {
            [SVProgressHUD showErrorWithStatus:errorMsgInfoRsp(jsonRsp)];
            
            [SVProgressHUD dismiss];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgInfoRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_teaCallNameInfoArr count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TeacherCallNameConfirmCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([TeacherCallNameConfirmCell class])];
    [cell setBackgroundColor:[UIColor whiteColor]];
    ASLoginUserInfo* subOrClaInfo =  [_teaCallNameInfoArr objectAtIndex:indexPath.row];
    //正常没请假的可以点名
    if ([subOrClaInfo.leaveType isEqualToString:@"0"]) {
        cell.callNameBtn.hidden = NO;
        cell.lateBtn.hidden = NO;
        cell.callStustatusLab.hidden = YES;
        [cell setselectCallName:subOrClaInfo.status];
        cell.lateBtn.tag = 100*indexPath.row + 2;
        cell.callNameBtn.tag = 100*indexPath.row + 3;
        cell.leaveBtn.tag = 100*indexPath.row + 1;
        cell.delegate = self;
    }
    else
    {
        cell.callStustatusLab.hidden = NO;
        cell.callStustatusLab.text = @"待审核";
        if ([subOrClaInfo.leaveType isEqualToString:@"1"]) {
            cell.callStustatusLab.text = @"审核通过";
        }
        cell.callNameBtn.hidden = YES;
        cell.lateBtn.hidden = YES;
    }
    
    cell.nameLab.text = subOrClaInfo.userName;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CallNameCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)getIsSelect:(NSInteger)index
{
    long row = index/100;
    
    ASLoginUserInfo* subclaInfo = [_teaCallNameInfoArr objectAtIndex:row];
    long status = [subclaInfo.status integerValue];
    if([_callNameUserArr containsObject:subclaInfo])
    {
        [_callNameUserArr removeObject:subclaInfo];
        if (status == index%100) {
            subclaInfo.status = [NSString stringWithFormat:@"%d",defaultCallNameSelectTag];
            
        }
        else
        {
            subclaInfo.status = [NSString stringWithFormat:@"%ld",index%100];
            [_callNameUserArr addObject:subclaInfo];
        }
        
    }
    else
    {
        subclaInfo.status = [NSString stringWithFormat:@"%ld",index%100];
        [_callNameUserArr addObject:subclaInfo];
    }

    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:0];
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

-(void)callName
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
